package com.hdw.cms.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hdw.basic.model.SystemContext;
import com.hdw.cms.dto.AjaxObj;
import com.hdw.cms.dto.IndexPicDto;
import com.hdw.cms.model.BaseInfo;
import com.hdw.cms.model.IndexPic;
import com.hdw.cms.service.AttachmentService;
import com.hdw.cms.service.IndexPicService;
import com.hdw.cms.service.IndexService;
import com.hdw.cms.utils.JsonUtil;


@Controller
@RequestMapping("/admin/pic")
public class IndexPicController {
	public final static int IMG_WIDTH = 900;
	public final static int THUMBNAIL_WIDTH = 280;
	public final static int THUMBNAIL_HEIGHT = 170;
	public final static int FLOAT_RightW1 = 130;
	public final static int FLOAT_RightH1 = 120;
	public final static int FLOAT_RightWO = 130;
	public final static int FLOAT_RightHO = 30;
	public final static int FLOAT_LeftW= 130;
	public final static int FLOAT_LeftH = 70;
	public final static int LogoW= 50;
	public final static int LogoH = 50;
	@Resource(name="indexPicService")
	private IndexPicService indexPicService;
	
	@Resource(name="attachmentService")
	private AttachmentService attachmentService;
	
	@Resource(name="indexService")
	private IndexService indexService;
	public final static String FILE_PATH="/resources/indexPic";
	public final static int T_W = 120;
	

	@RequestMapping("/indexPics.do")
	public String listIndexPic(Model model) {
		Map<String,Integer> mm = indexPicService.getMinAdnMaxPos();
		model.addAttribute("min", mm.get("min"));
		model.addAttribute("max", mm.get("max"));
		model.addAttribute("datas",indexPicService.findIndexPic());
		return "pic/listIndexPic";
	}
	@RequestMapping(value="/addIndexPic.do",method=RequestMethod.GET)
	public String addIndexPic(Model model) {
		IndexPic ip = new IndexPic();
		ip.setStatus(1);
		model.addAttribute("indexPic", ip);
		return "pic/addIndexPic";
	}
	
	@RequestMapping(value="/addIndexPic.do",method=RequestMethod.POST)
	public String addIndexPic(@Validated IndexPic indexPic,BindingResult br) {
		if(br.hasFieldErrors()) {
			return "pic/addIndexPic";
		}
		indexPicService.add(indexPic);
		if(indexPic.getStatus()!=0) {
		  indexService.generatebanner();
		}
		return "redirect:/jsp/common/addSuc.jsp";
	}
	
	@RequestMapping(value="/updateIndexPic/{id}.do",method=RequestMethod.GET)
	public String updateIndexPic(@PathVariable int id,Model model) {
		IndexPic ip = indexPicService.load(id);
		model.addAttribute("indexPic", ip);
		return "pic/updateIndexPic";
	}
	
	@RequestMapping(value="/updateIndexPic/{id}.do",method=RequestMethod.POST)
	public String updateIndexPic(@PathVariable int id,@Validated IndexPic indexPic,BindingResult br) {
		if(br.hasErrors()) {
			return "pic/updateIndexPic";
		}
		IndexPic tip = indexPicService.load(id);
		tip.setLinkType(indexPic.getLinkType());
		tip.setLinkUrl(indexPic.getLinkUrl());
		tip.setNewName(indexPic.getNewName());
		tip.setOldName(indexPic.getOldName());
		tip.setStatus(indexPic.getStatus());
		tip.setSubTitle(indexPic.getSubTitle());
		tip.setTitle(indexPic.getTitle());
		indexPicService.update(tip);
		indexService.generatebanner();
		indexService.generateTop();
		indexService.generateBody();
		return "redirect:/jsp/common/updateSuc.jsp";
	}
	
	@RequestMapping(value="/indexPic/{id}.do")
	public String showIndexPic(@PathVariable int id,Model model) {
		model.addAttribute("indexPic",indexPicService.load(id));
		return "pic/showIndexPic";
	}
	
	@RequestMapping(value="/deleteIndexPic/{id}.do")
	public String deleteIndexPic(@PathVariable int id) {
		indexPicService.delete(id);
		indexService.generatebanner();
		indexService.generateTop();
		indexService.generateBody();
		return "redirect:/admin/pic/indexPics.do";
	}
	
	@RequestMapping(value="updateIndexPicStatus/{id}.do")
	public String updateIndexPicStatus(@PathVariable int id) {
		indexPicService.updateStatus(id);
		indexService.generatebanner();
		indexService.generateTop();
		indexService.generateBody();
		return "redirect:/admin/pic/indexPics.do";
	}
	
	@RequestMapping(value="/uploadIndexPic.do",method=RequestMethod.POST)
	public void uploadIndexPic(HttpSession session,HttpServletResponse resp,MultipartFile pic,String isAdv) {
		resp.setContentType("text/plain;charset=utf-8");
		AjaxObj ao = new AjaxObj();
		PrintWriter out = null;
		String oldName = pic.getOriginalFilename();
		String newName = new Date().getTime()+"."+FilenameUtils.getExtension(oldName);
		String realPath = session.getServletContext().getRealPath("");
		if("1".equals(isAdv)){
			try {
				IndexPicDto ipd = new IndexPicDto();
				ipd.setNewName(newName);
				out = resp.getWriter();
				ao.setObj(ipd);
				ao.setResult(1);
				this.addAdvPic(newName, pic.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				out = resp.getWriter();
				File f = new File(realPath+FILE_PATH+"/temp");
				if(!f.exists()) {
					f.mkdirs();
				}
				//从属性文件中获取需要设置的图片的宽度和高度
				BaseInfo baseInfo = (BaseInfo)session.getServletContext().getAttribute("baseInfo");
				double w = baseInfo.getIndexPicWidth();
				double h = baseInfo.getIndexPicHeight();
				BufferedImage bi = ImageIO.read(pic.getInputStream());
				double nw = bi.getWidth();
				double nh = bi.getHeight();
				if(nw>=w&&nh>=h) {
					//图片的大小符合要求
					//判断是否进行缩放
					Builder<BufferedImage> b = Thumbnails.of(bi);
					if(nw-w>150) {
						b.scale((w+150)/nw);
					} else {
						b.scale(1.0);
					}
					BufferedImage bi2 = b.asBufferedImage();
					b.toFile(realPath+FILE_PATH+"/temp/"+newName);
					IndexPicDto ipd = new IndexPicDto();
					ipd.setNewName(newName);
					ipd.setOldName(oldName);
					ipd.setIndexPicHeight(new Double(h).intValue());
					ipd.setIndexPicWidth(new Double(w).intValue());
					ipd.setImgWidth(bi2.getWidth());
					ipd.setImgHeight(bi2.getHeight());
					ao.setObj(ipd);
					ao.setResult(1);
				} else {
					ao.setResult(0);
					ao.setMsg("图片的尺寸不在有效范围中");
				}
			} catch (IOException e) {
				ao.setResult(0);
				ao.setMsg(e.getMessage());
			}
		}
		out.println(JsonUtil.getInstance().obj2json(ao));
		out.flush();
	}
	
	@RequestMapping(value="/confirmPic.do",method=RequestMethod.POST)
	public @ResponseBody AjaxObj confirmPic(HttpSession session,int x,int y,int w,int h,String newName) {
		AjaxObj ao = new AjaxObj();
		try {
			BaseInfo baseInfo = (BaseInfo)session.getServletContext().getAttribute("baseInfo");
			int pw = baseInfo.getIndexPicWidth();
			int ph = baseInfo.getIndexPicHeight();
			String path = session.getServletContext().getRealPath("");
			String tpath = path+FILE_PATH+"/temp/"+newName;
			String tpath1 = path+FILE_PATH+"/temp/";
			File f = new File(tpath1);
			if(!f.exists()) {
				f.mkdirs();
			}
			
			File tf = new File(tpath);
			BufferedImage bi = ImageIO.read(tf);
			String npath = path+FILE_PATH+"/"+newName;
			String ttpath = path+FILE_PATH+"/thumbnail/"+newName;
			String ttpath1 = path+FILE_PATH+"/thumbnail/";
			
			File f1 = new File(ttpath1);
			if(!f1.exists()) {
				f1.mkdirs();
			}
			
			Builder<BufferedImage> b = Thumbnails.of(bi);
			//写原图
			BufferedImage bi2 = b.sourceRegion(x, y, w, h).size(pw, ph).asBufferedImage();
			b.toFile(npath);
			//写缩略图
			Thumbnails.of(bi2).scale((double)T_W/(double)pw).toFile(ttpath);
			tf.delete();
			ao.setResult(1);
			return ao;
		} catch (IOException e) {
			e.printStackTrace();
			ao.setResult(0);
			ao.setMsg(e.getMessage());
		}
		return ao;
	}
	
	@RequestMapping(value="/addAdvPic.do",method=RequestMethod.GET)
	public String addIndexAdvPic(Model model) {
		IndexPic ip = new IndexPic();
		ip.setStatus(1);
		model.addAttribute("indexPic", ip);
		return "pic/addAdvPic";
	}
	
	@RequestMapping(value="/addAdvPic.do",method=RequestMethod.POST)
	public String addIndexAdvPic(@Validated IndexPic indexPic,BindingResult br) {
		if(br.hasFieldErrors()) {
			return "pic/addIndexPic";
		}
		indexPicService.add(indexPic);
		indexService.generatebanner();
		indexService.generateBody();
		indexService.generateTop();
		return "redirect:/jsp/common/addSuc.jsp";
	}
	
	@SuppressWarnings("unused") 
	private void addAdvPic(String newName, InputStream is) throws IOException {
		// 进行文件的存储
		String realPath = SystemContext.getRealPath();
		String path = realPath + "/resources/indexPic/";
		String thumbPath = realPath + "/resources/indexPic/thumbnail/";
		String NewthumbPath = realPath + "/resources/indexPic/Newthumbnail/";
		String RightPath = realPath + "/resources/indexPic/FloatRight/";
		//改成了微信号
		String LeftPath = realPath + "/resources/indexPic/FloatLeft/";
		String LogoPath = realPath + "/resources/indexPic/Logo/";
		File fp = new File(path);
		File tfp = new File(thumbPath);
		File ntfp = new File(NewthumbPath);
		File rp = new File(RightPath);
		File lp = new File(LeftPath);
		File op=new File(LogoPath);
		// System.out.println(fp.exists());
		// System.out.println(tfp.exists());
		if (!fp.exists())
			fp.mkdirs();
		if (!tfp.exists())
			tfp.mkdirs();
		if (!ntfp.exists())
			ntfp.mkdirs();
		if(!lp.exists())
			lp.mkdirs();
		if(!rp.exists())
			rp.mkdirs();
		if(!op.exists())
			op.mkdirs();
		path = path + newName;
		thumbPath = thumbPath + newName;
		NewthumbPath = NewthumbPath + newName;
		LeftPath=LeftPath+newName;
		RightPath=RightPath+newName;
		LogoPath=LogoPath+newName;
		BufferedImage oldBi = ImageIO.read(is);
		int width = oldBi.getWidth();
		int hight = oldBi.getHeight();
		Builder<BufferedImage> bf = Thumbnails.of(oldBi);
		if (width > IMG_WIDTH) {
			bf.scale((double) IMG_WIDTH / (double) width);
		} else {
			bf.scale(1.0f);
		}
		bf.toFile(path);
		Thumbnails.of(oldBi).forceSize(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT).toFile(thumbPath);
		Thumbnails.of(oldBi).forceSize(FLOAT_RightW1, FLOAT_RightH1).toFile(NewthumbPath);
		Thumbnails.of(oldBi).forceSize(FLOAT_RightWO, FLOAT_RightHO).toFile(RightPath);
		Thumbnails.of(oldBi).forceSize(FLOAT_LeftW, FLOAT_LeftH).toFile(LeftPath);
		Thumbnails.of(oldBi).forceSize(LogoW, LogoH).toFile(LogoPath);
	}
}
